<!doctype html>



  


<html class="theme-next muse use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>









<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />




  
  
  
  

  
    
    
  

  

  

  

  

  
    
    
    <link href="//fonts.googleapis.com/css?family=Lato:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
  






<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.1" rel="stylesheet" type="text/css" />


  <meta name="keywords" content="java,netty," />








  <link rel="shortcut icon" type="image/x-icon" href="/favicon.ico?v=5.1.1" />






<meta name="description" content="前言目前主流的JAVA web 的HTTP服务主要是 springMVC和Struts2，更早的有JSP/servlet。在学习Netty的时候，发现Netty 也可以作HTTP服务，于是便将此整理一篇博文，分享给大家。 开发准备添加配置将Netty作为HTTP服务，需要在过滤器中添加HttpRequest之类的配置，如:  123      ph.addLast(&amp;quot;encoder&amp;qu">
<meta name="keywords" content="java,netty">
<meta property="og:type" content="article">
<meta property="og:title" content="Netty4 学习笔记之四- Netty HTTP服务的实现">
<meta property="og:url" content="http://yoursite.com/2017/10/27/Netty4 学习笔记之四- Netty HTTP服务的实现/index.html">
<meta property="og:site_name" content="xuwujing&#39;s blog">
<meta property="og:description" content="前言目前主流的JAVA web 的HTTP服务主要是 springMVC和Struts2，更早的有JSP/servlet。在学习Netty的时候，发现Netty 也可以作HTTP服务，于是便将此整理一篇博文，分享给大家。 开发准备添加配置将Netty作为HTTP服务，需要在过滤器中添加HttpRequest之类的配置，如:  123      ph.addLast(&amp;quot;encoder&amp;qu">
<meta property="og:image" content="http://img.blog.csdn.net/20171027133307620?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvcWF6d3N4cGNt/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/SouthEast">
<meta property="og:image" content="http://img.blog.csdn.net/20171027133317644?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvcWF6d3N4cGNt/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/SouthEast">
<meta property="og:image" content="http://img.blog.csdn.net/20171027133753199?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvcWF6d3N4cGNt/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/SouthEast">
<meta property="og:image" content="http://img.blog.csdn.net/20171027133742427?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvcWF6d3N4cGNt/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/SouthEast">
<meta property="og:image" content="http://img.blog.csdn.net/20171027133824027?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvcWF6d3N4cGNt/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/SouthEast">
<meta property="og:image" content="http://img.blog.csdn.net/20171027133930228?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvcWF6d3N4cGNt/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/SouthEast">
<meta property="og:image" content="http://img.blog.csdn.net/20171027133937128?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvcWF6d3N4cGNt/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/SouthEast">
<meta property="og:updated_time" content="2017-11-18T02:47:59.819Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Netty4 学习笔记之四- Netty HTTP服务的实现">
<meta name="twitter:description" content="前言目前主流的JAVA web 的HTTP服务主要是 springMVC和Struts2，更早的有JSP/servlet。在学习Netty的时候，发现Netty 也可以作HTTP服务，于是便将此整理一篇博文，分享给大家。 开发准备添加配置将Netty作为HTTP服务，需要在过滤器中添加HttpRequest之类的配置，如:  123      ph.addLast(&amp;quot;encoder&amp;qu">
<meta name="twitter:image" content="http://img.blog.csdn.net/20171027133307620?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvcWF6d3N4cGNt/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/SouthEast">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Muse',
    sidebar: {"position":"left","display":"post","offset":12,"offset_float":0,"b2t":false,"scrollpercent":false},
    fancybox: true,
    motion: true,
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://yoursite.com/2017/10/27/Netty4 学习笔记之四- Netty HTTP服务的实现/"/>





  <title>Netty4 学习笔记之四- Netty HTTP服务的实现 | xuwujing's blog</title>
  





  <script type="text/javascript">
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "https://hm.baidu.com/hm.js?39c177d10f6e05ddfa113e02139b9c1c";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>










</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail ">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">xuwujing's blog</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle"></p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal " itemscope itemtype="http://schema.org/Article">
    <link itemprop="mainEntityOfPage" href="http://yoursite.com/2017/10/27/Netty4 学习笔记之四- Netty HTTP服务的实现/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="xuwujing">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/xuwujing.png">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="xuwujing's blog">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">Netty4 学习笔记之四- Netty HTTP服务的实现</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2017-10-27T13:43:00+08:00">
                2017-10-27
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/netty/" itemprop="url" rel="index">
                    <span itemprop="name">netty</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          

          

          

        </div>
      </header>
    

    <div class="post-body" itemprop="articleBody">

      
      

      
        <h2 id="前言"><a href="#前言" class="headerlink" title="前言"></a>前言</h2><p>目前主流的JAVA web 的HTTP服务主要是 springMVC和Struts2，更早的有JSP/servlet。<br>在学习Netty的时候，发现Netty 也可以作HTTP服务，于是便将此整理一篇博文，分享给大家。</p>
<h2 id="开发准备"><a href="#开发准备" class="headerlink" title="开发准备"></a>开发准备</h2><h3 id="添加配置"><a href="#添加配置" class="headerlink" title="添加配置"></a>添加配置</h3><p>将Netty作为HTTP服务，需要在过滤器中添加HttpRequest之类的配置，如: </p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div></pre></td><td class="code"><pre><div class="line">      ph.addLast(&quot;encoder&quot;,new HttpResponseEncoder());</div><div class="line">      ph.addLast(&quot;decoder&quot;,new HttpRequestDecoder());</div><div class="line">ph.addLast(&quot;aggregator&quot;, new HttpObjectAggregator(10*1024*1024));</div></pre></td></tr></table></figure>
<p>基本配置和之前的<a href="http://blog.csdn.net/qazwsxpcm/article/details/77750865" target="_blank" rel="external">客户端和服务端通信Demo</a>几乎一样，就是在业务处理器中略微的修改下业务逻辑处理就可以了。</p>
<h3 id="HTTP-GET请求测试"><a href="#HTTP-GET请求测试" class="headerlink" title="HTTP GET请求测试"></a>HTTP GET请求测试</h3><p>那么进行测试。<br>首先启动Netty服务，然后使用HTTP GET 方式测试(直接在浏览器上输入<a href="http://localhost:6789/test" target="_blank" rel="external">http://localhost:6789/test</a>)<br>结果如下:<br><img src="http://img.blog.csdn.net/20171027133307620?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvcWF6d3N4cGNt/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/SouthEast" alt="这里写图片描述"><br><img src="http://img.blog.csdn.net/20171027133317644?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvcWF6d3N4cGNt/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/SouthEast" alt="这里写图片描述"></p>
<h3 id="HTTP服务准备"><a href="#HTTP服务准备" class="headerlink" title="HTTP服务准备"></a>HTTP服务准备</h3><p>一般来说，使用<strong>HttpRequest</strong> 类作为请求，但是该类中没有获取消息体的方法，获取消息体的类为<strong>HttpContent</strong> 或<strong>LastHttpContent</strong>，这样获取请求和消息体则相当不对不方便。<br>在查阅Netty相关资料后，发现这样一个请求类，可以完成上述所提的要求。这个类就是<strong>FullHttpRequest</strong>。<br>查看该类源码，可以发现该类继承<strong>HttpRequest</strong>, <strong>FullHttpMessage</strong>，而<strong>FullHttpMessage</strong>又继承<strong>LastHttpContent</strong>， 而<strong>LastHttpContent</strong>又继承<strong>HttpContent</strong>，所以该类可以实现上述要求。<br>源码示例图:<br><img src="http://img.blog.csdn.net/20171027133753199?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvcWF6d3N4cGNt/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/SouthEast" alt="这里写图片描述"></p>
<p><img src="http://img.blog.csdn.net/20171027133742427?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvcWF6d3N4cGNt/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/SouthEast" alt="这里写图片描述"></p>
<p><img src="http://img.blog.csdn.net/20171027133824027?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvcWF6d3N4cGNt/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/SouthEast" alt="这里写图片描述"></p>
<p>那么代码修改如下:</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div></pre></td><td class="code"><pre><div class="line">      FullHttpRequest httpRequest = (FullHttpRequest)msg;</div><div class="line">      String path=httpRequest.uri();			//获取路径</div><div class="line">String body = getBody(httpRequest); 	//获取参数</div><div class="line">HttpMethod method=httpRequest.method();//获取请求方法</div></pre></td></tr></table></figure>
<p>然后测试POST、PUT和DELETE请求并使用json格式传输。<br>我们可以通过postman等工具来直接调用，就不用写相关请求代码了<br><img src="http://img.blog.csdn.net/20171027133930228?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvcWF6d3N4cGNt/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/SouthEast" alt="这里写图片描述"></p>
<p><img src="http://img.blog.csdn.net/20171027133937128?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvcWF6d3N4cGNt/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/SouthEast" alt="这里写图片描述"></p>
<p>可以看见，Netty 作为HTTP服务可以接受基本的请求。</p>
<p>完整的代码如下:</p>
<p><strong>服务端:</strong></p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div><div class="line">33</div><div class="line">34</div><div class="line">35</div><div class="line">36</div><div class="line">37</div><div class="line">38</div><div class="line">39</div></pre></td><td class="code"><pre><div class="line">import io.netty.bootstrap.ServerBootstrap;</div><div class="line">import io.netty.channel.ChannelFuture;</div><div class="line">import io.netty.channel.EventLoopGroup;</div><div class="line">import io.netty.channel.nio.NioEventLoopGroup;</div><div class="line">import io.netty.channel.socket.nio.NioServerSocketChannel;</div><div class="line"></div><div class="line"></div><div class="line">/**</div><div class="line"> * </div><div class="line">* Title: NettyServer</div><div class="line">* Description: Netty服务端  Http测试</div><div class="line">* Version:1.0.0  </div><div class="line">* @author pancm</div><div class="line">* @date 2017年10月26日</div><div class="line"> */</div><div class="line">public class NettyServer &#123;</div><div class="line">	    private static final int port = 6789; //设置服务端端口</div><div class="line">	    private static  EventLoopGroup group = new NioEventLoopGroup();   // 通过nio方式来接收连接和处理连接   </div><div class="line">	    private static  ServerBootstrap b = new ServerBootstrap();</div><div class="line">	    </div><div class="line">	    /**</div><div class="line">		 * Netty创建全部都是实现自AbstractBootstrap。</div><div class="line">		 * 客户端的是Bootstrap，服务端的则是	ServerBootstrap。</div><div class="line">		 **/</div><div class="line">	    public static void main(String[] args) throws InterruptedException &#123;</div><div class="line">	        try &#123;</div><div class="line">	            b.group(group);</div><div class="line">	            b.channel(NioServerSocketChannel.class);</div><div class="line">	            b.childHandler(new NettyServerFilter()); //设置过滤器</div><div class="line">	            // 服务器绑定端口监听</div><div class="line">	            ChannelFuture f = b.bind(port).sync();</div><div class="line">	            System.out.println(&quot;服务端启动成功,端口是:&quot;+port);</div><div class="line">	            // 监听服务器关闭监听</div><div class="line">	            f.channel().closeFuture().sync();</div><div class="line">	        &#125; finally &#123;</div><div class="line">	            group.shutdownGracefully(); //关闭EventLoopGroup，释放掉所有资源包括创建的线程  </div><div class="line">	        &#125;</div><div class="line">	    &#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p><strong>服务端过滤器:</strong></p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div></pre></td><td class="code"><pre><div class="line">import io.netty.channel.ChannelInitializer;</div><div class="line">import io.netty.channel.ChannelPipeline;</div><div class="line">import io.netty.channel.socket.SocketChannel;</div><div class="line">import io.netty.handler.codec.http.HttpServerCodec;</div><div class="line"> </div><div class="line"></div><div class="line">/**</div><div class="line"> * </div><div class="line">* Title: NettyServerFilter</div><div class="line">* Description: Netty 服务端过滤器</div><div class="line">* Version:1.0.0  </div><div class="line">* @author pancm</div><div class="line">* @date 2017年10月26日</div><div class="line"> */</div><div class="line">public class NettyServerFilter extends ChannelInitializer&lt;SocketChannel&gt; &#123;</div><div class="line"> </div><div class="line">     @Override</div><div class="line">     protected void initChannel(SocketChannel ch) throws Exception &#123;</div><div class="line">         ChannelPipeline ph = ch.pipeline();</div><div class="line">         //处理http服务的关键handler</div><div class="line">      ph.addLast(&quot;encoder&quot;,new HttpResponseEncoder());</div><div class="line">         ph.addLast(&quot;decoder&quot;,new HttpRequestDecoder());</div><div class="line">         ph.addLast(&quot;aggregator&quot;, new HttpObjectAggregator(10*1024*1024)); </div><div class="line">ph.addLast(&quot;handler&quot;, new NettyServerHandler());// 服务端业务逻辑</div><div class="line">     &#125;</div><div class="line"> &#125;</div></pre></td></tr></table></figure>
<p><strong>服务端业务逻辑</strong></p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div><div class="line">33</div><div class="line">34</div><div class="line">35</div><div class="line">36</div><div class="line">37</div><div class="line">38</div><div class="line">39</div><div class="line">40</div><div class="line">41</div><div class="line">42</div><div class="line">43</div><div class="line">44</div><div class="line">45</div><div class="line">46</div><div class="line">47</div><div class="line">48</div><div class="line">49</div><div class="line">50</div><div class="line">51</div><div class="line">52</div><div class="line">53</div><div class="line">54</div><div class="line">55</div><div class="line">56</div><div class="line">57</div><div class="line">58</div><div class="line">59</div><div class="line">60</div><div class="line">61</div><div class="line">62</div><div class="line">63</div><div class="line">64</div><div class="line">65</div><div class="line">66</div><div class="line">67</div><div class="line">68</div><div class="line">69</div><div class="line">70</div><div class="line">71</div><div class="line">72</div><div class="line">73</div><div class="line">74</div><div class="line">75</div><div class="line">76</div><div class="line">77</div><div class="line">78</div><div class="line">79</div><div class="line">80</div><div class="line">81</div><div class="line">82</div><div class="line">83</div><div class="line">84</div><div class="line">85</div><div class="line">86</div><div class="line">87</div><div class="line">88</div><div class="line">89</div><div class="line">90</div><div class="line">91</div><div class="line">92</div><div class="line">93</div><div class="line">94</div><div class="line">95</div><div class="line">96</div><div class="line">97</div><div class="line">98</div><div class="line">99</div><div class="line">100</div><div class="line">101</div><div class="line">102</div><div class="line">103</div><div class="line">104</div><div class="line">105</div><div class="line">106</div><div class="line">107</div><div class="line">108</div><div class="line">109</div><div class="line">110</div><div class="line">111</div><div class="line">112</div><div class="line">113</div><div class="line">114</div><div class="line">115</div><div class="line">116</div><div class="line">117</div><div class="line">118</div><div class="line">119</div><div class="line">120</div></pre></td><td class="code"><pre><div class="line">import io.netty.buffer.ByteBuf;</div><div class="line">import io.netty.buffer.Unpooled;</div><div class="line">import io.netty.channel.ChannelFutureListener;</div><div class="line">import io.netty.channel.ChannelHandlerContext;</div><div class="line">import io.netty.channel.ChannelInboundHandlerAdapter;</div><div class="line">import io.netty.handler.codec.http.DefaultFullHttpResponse;</div><div class="line">import io.netty.handler.codec.http.FullHttpRequest;</div><div class="line">import io.netty.handler.codec.http.FullHttpResponse;</div><div class="line">import io.netty.handler.codec.http.HttpHeaderNames;</div><div class="line">import io.netty.handler.codec.http.HttpMethod;</div><div class="line">import io.netty.handler.codec.http.HttpResponseStatus;</div><div class="line">import io.netty.handler.codec.http.HttpVersion;</div><div class="line">import io.netty.util.CharsetUtil;</div><div class="line">import java.net.InetAddress;</div><div class="line"></div><div class="line">/**</div><div class="line"> * </div><div class="line">* Title: NettyServerHandler</div><div class="line">* Description: 服务端业务逻辑</div><div class="line">* Version:1.0.0  </div><div class="line">* @author pancm</div><div class="line">* @date 2017年10月26日</div><div class="line"> */</div><div class="line">public class NettyServerHandler extends ChannelInboundHandlerAdapter &#123;</div><div class="line">	private String result=&quot;&quot;;</div><div class="line">	/*</div><div class="line">	 * 收到消息时，返回信息</div><div class="line">	 */</div><div class="line">	@Override</div><div class="line">	public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception &#123;</div><div class="line">		if(! (msg instanceof FullHttpRequest))&#123;</div><div class="line">			result=&quot;未知请求!&quot;;</div><div class="line">			send(ctx,result,HttpResponseStatus.BAD_REQUEST);</div><div class="line">			return;</div><div class="line">	 	&#125;</div><div class="line">				FullHttpRequest httpRequest = (FullHttpRequest)msg;</div><div class="line">		try&#123;</div><div class="line">			String path=httpRequest.uri();			//获取路径</div><div class="line">			String body = getBody(httpRequest); 	//获取参数</div><div class="line">			HttpMethod method=httpRequest.method();//获取请求方法</div><div class="line">			//如果不是这个路径，就直接返回错误</div><div class="line">			if(!&quot;/test&quot;.equalsIgnoreCase(path))&#123;</div><div class="line">				result=&quot;非法请求!&quot;;</div><div class="line">				send(ctx,result,HttpResponseStatus.BAD_REQUEST);</div><div class="line">				return;</div><div class="line">			&#125;</div><div class="line">			System.out.println(&quot;接收到:&quot;+method+&quot; 请求&quot;);</div><div class="line">			//如果是GET请求</div><div class="line">			if(HttpMethod.GET.equals(method))&#123; </div><div class="line">				//接受到的消息，做业务逻辑处理...</div><div class="line">				System.out.println(&quot;body:&quot;+body);</div><div class="line">				result=&quot;GET请求&quot;;</div><div class="line">				send(ctx,result,HttpResponseStatus.OK);</div><div class="line">				return;</div><div class="line">			&#125;</div><div class="line">			//如果是POST请求</div><div class="line">			if(HttpMethod.POST.equals(method))&#123; </div><div class="line">				//接受到的消息，做业务逻辑处理...</div><div class="line">				System.out.println(&quot;body:&quot;+body);</div><div class="line">				result=&quot;POST请求&quot;;</div><div class="line">				send(ctx,result,HttpResponseStatus.OK);</div><div class="line">				return;</div><div class="line">			&#125;</div><div class="line">			</div><div class="line">			//如果是PUT请求</div><div class="line">			if(HttpMethod.PUT.equals(method))&#123; </div><div class="line">				//接受到的消息，做业务逻辑处理...</div><div class="line">				System.out.println(&quot;body:&quot;+body);</div><div class="line">				result=&quot;PUT请求&quot;;</div><div class="line">				send(ctx,result,HttpResponseStatus.OK);</div><div class="line">				return;</div><div class="line">			&#125;</div><div class="line">			//如果是DELETE请求</div><div class="line">			if(HttpMethod.DELETE.equals(method))&#123; </div><div class="line">				//接受到的消息，做业务逻辑处理...</div><div class="line">				System.out.println(&quot;body:&quot;+body);</div><div class="line">				result=&quot;DELETE请求&quot;;</div><div class="line">				send(ctx,result,HttpResponseStatus.OK);</div><div class="line">				return;</div><div class="line">			&#125;</div><div class="line">		&#125;catch(Exception e)&#123;</div><div class="line">			System.out.println(&quot;处理请求失败!&quot;);</div><div class="line">			e.printStackTrace();</div><div class="line">		&#125;finally&#123;</div><div class="line">			//释放请求</div><div class="line">			httpRequest.release();</div><div class="line">		&#125;   </div><div class="line">	&#125;	</div><div class="line">	/**</div><div class="line">	 * 获取body参数</div><div class="line">	 * @param request</div><div class="line">	 * @return</div><div class="line">	 */</div><div class="line">	private String getBody(FullHttpRequest request)&#123;</div><div class="line">		ByteBuf buf = request.content();</div><div class="line">		return buf.toString(CharsetUtil.UTF_8);</div><div class="line">	&#125;</div><div class="line">	</div><div class="line">	/**</div><div class="line">	 * 发送的返回值</div><div class="line">	 * @param ctx	  返回</div><div class="line">	 * @param context 消息</div><div class="line">	 * @param status 状态</div><div class="line">	 */</div><div class="line">	private void send(ChannelHandlerContext ctx, String context,HttpResponseStatus status) &#123;</div><div class="line">		FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, status, Unpooled.copiedBuffer(context, CharsetUtil.UTF_8));</div><div class="line">		response.headers().set(HttpHeaderNames.CONTENT_TYPE, &quot;text/plain; charset=UTF-8&quot;);</div><div class="line">		ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);</div><div class="line">	&#125;</div><div class="line">	</div><div class="line">	/*</div><div class="line">	 * 建立连接时，返回消息</div><div class="line">	 */</div><div class="line">	@Override</div><div class="line">	public void channelActive(ChannelHandlerContext ctx) throws Exception &#123;</div><div class="line">		System.out.println(&quot;连接的客户端地址:&quot; + ctx.channel().remoteAddress());</div><div class="line">		ctx.writeAndFlush(&quot;客户端&quot;+ InetAddress.getLocalHost().getHostName() + &quot;成功与服务端建立连接！ &quot;);</div><div class="line">		super.channelActive(ctx);</div><div class="line">	&#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<h2 id="结语"><a href="#结语" class="headerlink" title="结语"></a>结语</h2><p>那么Netty HTTP 服务的相关测试就到这了，如果有什么疑问，欢迎讨论！</p>

      
    </div>

    <div>
      
        

      
    </div>

    <div>
      
        

      
    </div>

    <div>
      
        

      
    </div>

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/java/" rel="tag"># java</a>
          
            <a href="/tags/netty/" rel="tag"># netty</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2017/10/21/分享一些JAVA相关资源/" rel="next" title="分享一些JAVA相关资源">
                <i class="fa fa-chevron-left"></i> 分享一些JAVA相关资源
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2017/11/03/JAVA常用工具类/" rel="prev" title="JAVA常用工具类">
                JAVA常用工具类 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          
  <div class="comments" id="comments">
    
  </div>


        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap" >
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
          <img class="site-author-image" itemprop="image"
               src="/images/xuwujing.png"
               alt="xuwujing" />
          <p class="site-author-name" itemprop="name">xuwujing</p>
           
              <p class="site-description motion-element" itemprop="description">The way of the future!</p>
          
        </div>
        <nav class="site-state motion-element">

          
            <div class="site-state-item site-state-posts">
              <a href="/archives/">
                <span class="site-state-item-count">56</span>
                <span class="site-state-item-name">日志</span>
              </a>
            </div>
          

          
            
            
            <div class="site-state-item site-state-categories">
              <a href="/categories/index.html">
                <span class="site-state-item-count">20</span>
                <span class="site-state-item-name">分类</span>
              </a>
            </div>
          

          
            
            
            <div class="site-state-item site-state-tags">
              <a href="/tags/index.html">
                <span class="site-state-item-count">36</span>
                <span class="site-state-item-name">标签</span>
              </a>
            </div>
          

        </nav>

        

        <div class="links-of-author motion-element">
          
            
              <span class="links-of-author-item">
                <a href="https://github.com/xuwujing" target="_blank" title="github">
                  
                    <i class="fa fa-fw fa-globe"></i>
                  
                  github
                </a>
              </span>
            
              <span class="links-of-author-item">
                <a href="http://blog.csdn.net/qazwsxpcm?viewmode=list" target="_blank" title="csdn">
                  
                    <i class="fa fa-fw fa-globe"></i>
                  
                  csdn
                </a>
              </span>
            
              <span class="links-of-author-item">
                <a href="https://home.cnblogs.com/u/xuwujing/" target="_blank" title="cnblogs">
                  
                    <i class="fa fa-fw fa-globe"></i>
                  
                  cnblogs
                </a>
              </span>
            
          
        </div>

        
        

        
        
          <div class="links-of-blogroll motion-element links-of-blogroll-inline">
            <div class="links-of-blogroll-title">
              <i class="fa  fa-fw fa-globe"></i>
              
            </div>
            <ul class="links-of-blogroll-list">
              
                <li class="links-of-blogroll-item">
                  <a href="http://www.woainia.site/" title="woainia" target="_blank">woainia</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="http://cmsblogs.com/" title="chenssy" target="_blank">chenssy</a>
                </li>
              
            </ul>
          </div>
        

        


      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#前言"><span class="nav-number">1.</span> <span class="nav-text">前言</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#开发准备"><span class="nav-number">2.</span> <span class="nav-text">开发准备</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#添加配置"><span class="nav-number">2.1.</span> <span class="nav-text">添加配置</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#HTTP-GET请求测试"><span class="nav-number">2.2.</span> <span class="nav-text">HTTP GET请求测试</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#HTTP服务准备"><span class="nav-number">2.3.</span> <span class="nav-text">HTTP服务准备</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#结语"><span class="nav-number">3.</span> <span class="nav-text">结语</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright" >
  
  &copy; 
  <span itemprop="copyrightYear">2017</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">xuwujing</span>
</div>


<div class="powered-by">
  由 <a class="theme-link" href="https://hexo.io">Hexo</a> 强力驱动
</div>

<div class="theme-info">
  主题 -
  <a class="theme-link" href="https://github.com/iissnan/hexo-theme-next">
    NexT.Muse
  </a>
</div>


        

        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>

  
  <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>

  
  <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>

  
  <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.1"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.1"></script>



  
  

  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.1"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.1"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.1"></script>



  


  




	





  





  





  






  





  

  

  

  

  

  

</body>
</html>
